//
//  HomeViewController.m
//  cm
//
//  Created by suyibaishan on 2017/10/25.
//  Copyright © 2017年 feihu. All rights reserved.
//

#import "HomeViewController.h"
#import "ImagePlayerView.h"
#import "CollectionViewCell.h"
#import "HeadView.h"
#import "GoodsViewController.h"
#import "NoticeViewController.h"
#import "SearchViewController.h"
#import "JoinViewController.h"
#import "BaseNavigationController.h"
#import "LoginViewController.h"
#import "IntegralViewController.h"

#define tabBarHeight  self.tabBarController.tabBar.frame.size.height

@interface HomeViewController () <UICollectionViewDelegate,UICollectionViewDataSource,ImagePlayerViewDelegate,UITextFieldDelegate>

@property (nonatomic,strong) ImagePlayerView *imagePlayerView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataSource;

@end

@implementation HomeViewController
{
    NSArray *imageArr;
    UITextField *searchField;
    UIView *headView;
    NSString *advertUrl;
    NSInteger page;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self reloadBannerList];
    
    [self reloadData];
    
    [self createHomeView];
}

-(void)reloadBannerList
{
    [[ToolNet sharedManager] getBannerList:1 url:MBannerList completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
        if ([responseJson[@"code"] isEqual:@1]) {
            imageArr = responseJson[@"data"];
        }
    }];
    [[ToolNet sharedManager] getBannerList:2 url:MBannerList completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
        if ([responseJson[@"code"] isEqual:@1]) {
            advertUrl = responseJson[@"data"][@"imgUrl"];
            NSLog(@"~~~~~~~advertUrl:%@",advertUrl);
        }
    }];
}

-(void)reloadData
{
    [[ToolNet sharedManager] getCarsList:nil pageNum:1 pageSize:16 url:MCarsList completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
        if ([responseJson[@"code"] isEqual:@1]) {
            [self.dataSource removeAllObjects];
            [self.dataSource addObjectsFromArray:responseJson[@"data"][@"list"]];
            [_collectionView reloadData];
            page = 2;
        }
        else {
            [self showMessage:responseJson[@"msg"]];
        }
        [_collectionView.mj_header endRefreshing];
        [_collectionView.mj_footer endRefreshing];
    }];
}

-(void)loadMoreData
{
    [[ToolNet sharedManager] getCarsList:nil pageNum:page pageSize:16 url:MCarsList completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
        if ([responseJson[@"code"] isEqual:@1]) {
            if ([responseJson[@"data"][@"pages"] integerValue] >= page) {
                [self.dataSource addObjectsFromArray:responseJson[@"data"][@"list"]];
                [_collectionView.mj_footer endRefreshing];
                page++;
            }
            else{
                [_collectionView.mj_footer endRefreshingWithNoMoreData];
            }
            [_collectionView reloadData];
        }
        else {
            [self showMessage:responseJson[@"msg"]];
            [_collectionView.mj_footer endRefreshing];
        }
    }];
}

-(void)createHomeView
{
    searchField = ({
        UIImageView *leftImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search"]];
        leftImage.contentMode = UIViewContentModeScaleAspectFit;
//        leftImage.frame = CGRectMake(0, 0, 20, 20);

        UITextField *tfield = [UITextField new];
        tfield.textAlignment = NSTextAlignmentCenter;
        [self.baseBar addSubview:tfield];
        tfield.rightView = leftImage;
        tfield.rightViewMode = UITextFieldViewModeAlways;
        [tfield.layer setCornerRadius:5.0];
        [tfield setFont:[UIFont systemFontOfSize:14]];
        tfield.clearButtonMode = UITextFieldViewModeAlways;
        tfield.backgroundColor = [UIColor colorWithRed:0.91 green:0.93 blue:0.93 alpha:1];
        tfield.textColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1];
        UIColor *color = [UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:1];
        tfield.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入关键字搜索" attributes:@{NSForegroundColorAttributeName: color}];
        tfield;
    });
    searchField.delegate = self;
    searchField.sd_layout
    .leftSpaceToView(self.baseBar, 15)
    .topSpaceToView(self.baseBar, statusBarRect.size.height+8)
    .widthIs(kScreenWidth - 30)
    .heightIs(28);
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.headerReferenceSize = CGSizeMake(kScreenWidth, (IS_IPHONE_8?170:IS_IPHONE_8PLUS?190:160)+180);
    layout.minimumInteritemSpacing = 0.f;
    layout.minimumLineSpacing = 0.5f;
    
    _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.backgroundColor = [UIColor colorWithRed:0.96 green:0.97 blue:0.97 alpha:1];
    [self.view addSubview:_collectionView];
    _collectionView.sd_layout
    .leftSpaceToView(self.view, 0)
    .topSpaceToView(self.baseBar, 0)
    .widthIs(kScreenWidth)
    .heightIs(kScreenHeight - self.baseBarHeight - tabBarHeight);
    
    [_collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentify"];
    [_collectionView registerClass:[HeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headIdentifier"];
    _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self reloadData];
    }];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    _collectionView.mj_header.automaticallyChangeAlpha = YES;
    _collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    
    self.dataSource = [NSMutableArray array];
}

#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIdentifier = @"cellIdentify";
    CollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.model = [[CollectionModel alloc] initWithDictionary:self.dataSource[indexPath.row]];
    
    return cell;
}

#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((kScreenWidth - 15)/2, (kScreenWidth - 15)/2+70);
}

//定义每个UICollectionView的margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 5, 5, 5);
}

#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    GoodsViewController *goodsVC = [[GoodsViewController alloc] init];
    goodsVC.dataSource = self.dataSource[indexPath.row];
    [self.navigationController pushViewController:goodsVC animated:YES];
}

//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    HeadView *headView;
    headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headIdentifier" forIndexPath:indexPath];
    
    _imagePlayerView = [[ImagePlayerView alloc] init];
    _imagePlayerView.scrollInterval = 5.0f;
    _imagePlayerView.hidePageControl = NO;
    _imagePlayerView.pageControlPosition = ICPageControlPosition_BottomCenter;
    [headView addSubview:_imagePlayerView];
    _imagePlayerView.sd_layout
    .topSpaceToView(headView, 0)
    .leftSpaceToView(headView, 0)
    .widthIs(kScreenWidth)
    .heightIs(IS_IPHONE_8?170:IS_IPHONE_8PLUS?190:160);
    [_imagePlayerView initWithCount:imageArr.count delegate:self];
    
    if (advertUrl) {
        [headView.advertView sd_setImageWithURL:[NSURL URLWithString:[kIMGURL stringByAppendingString:advertUrl]]];
    }
    
    [headView setAdImageClickBlock:^{
        if (![[mUserDefaults objectForKey:@"isLogin"] isEqualToString:@"1"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                BaseNavigationController *navController = [[BaseNavigationController alloc] initWithRootViewController:[LoginViewController new]];
                [mAppDelegate.window.rootViewController presentViewController:navController animated:YES completion:nil];
            });
        }
        else {
            if (![[mUserDefaults objectForKey:@"vip"] isEqual:@1]) {
                JoinViewController *joinVC = [[JoinViewController alloc] init];
                [self.navigationController pushViewController:joinVC animated:YES];
            }
            else {
                [self showMessage:@"您已经是VIP"];
            }
        }
    }];
    
    [headView setClickBlock:^(NSInteger tag) {
        if (tag == 100) {
            NoticeViewController *noticeVC = [[NoticeViewController alloc] init];
            [self.navigationController pushViewController:noticeVC animated:YES];
        }
        else if (tag == 101) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"SHOWMALLVIEW" object:nil];
        }else if (tag == 102) // 积分商城
        {
            IntegralViewController * integralVC = [[IntegralViewController alloc]init];
            [self.navigationController pushViewController:integralVC animated:YES];
        }
    }];

    return headView;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:NO];
    return NO;
}

#pragma mark - ImagePlayerViewDelegate
- (NSInteger)numberOfItems:(ImagePlayerView *)imagePlayerView
{
    return imageArr.count;
}

- (void)imagePlayerView:(ImagePlayerView *)imagePlayerView loadImageForImageView:(UIImageView *)imageView index:(NSInteger)index
{
    if (imageArr && imageArr.count > index) {
        [imageView sd_setImageWithURL:[NSURL URLWithString:[kIMGURL stringByAppendingString:imageArr[index][@"imgUrl"]]] placeholderImage:[UIImage imageNamed:@"holderImg"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if (image && cacheType == SDImageCacheTypeNone) {
                imageView.alpha = 0.0;
                [UIView transitionWithView:imageView
                                  duration:1.0
                                   options:UIViewAnimationOptionTransitionCrossDissolve
                                animations:^{
                                    [imageView setImage:image];
                                    imageView.alpha = 1.0;
                                } completion:NULL];
            }
        }];
    }
}

- (void)imagePlayerView:(ImagePlayerView *)imagePlayerView didTapAtIndex:(NSInteger)index
{
    if (![imageArr[index][@"linkUrl"] isEqualToString:@"#"]) {
        //        BannerViewController *bannerVC = [[BannerViewController alloc] init];
        //        bannerVC.webTitle = imageArr[index][@"title"];
        //        bannerVC.webUrl = imageArr[index][@"url"];
        //        [self.navigationController pushViewController:bannerVC animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
